//
//  RPNetworkExtensionTool.m
//  ShowYork
//
//  Created by hxh on 2020/12/30.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "RPNetworkExtensionTool.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "BindPhoneViewController.h"
#import "CampusVideoPlayerViewController.h"
@implementation RPNetworkExtensionTool

- (NSURLSessionTask *)requestPOST:(NSString *)URLString parames:(id)parames success:(void (^)(id))success failure:(void (^)(id))failure{

    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];
    if (parames != nil) {
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:parames];
        if ([RPAppManager isLogin]) {
            param[@"token"] = [RPAppManager getToken];
            param[@"tokenId"] = [RPAppManager getCustomerId];
        }
        param[@"version"] = @"14";
        NSData *jsonData = [param mj_JSONData];
        [request setHTTPBody:jsonData];
        NSLog(@"%@\n%@",URLString,param);
    }
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        
    [request addValue:app_Name forHTTPHeaderField:@"app"];
    [request addValue:@"iOS" forHTTPHeaderField:@"os"];
    [request addValue:app_Version forHTTPHeaderField:@"version"];
    [request addValue:@"14" forHTTPHeaderField:@"versionCode"];
    
    NSURLSessionTask *task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error) {
            if (error.code == -1001 || error.code == -1009 || error.code == -1004 || error.code == -1020) {
                NSInteger code = [responseObject[@"code"] integerValue];
                NSError *err = [NSError errorWithDomain:@"com.showYork.DDUP" code:code userInfo:@{@"info":@"网络好像有点问题，请检查后重试"}];
                failure(err);
            }else if(error.code != -999){
                failure(error);
            }
        }else{
            NSString *message = @"系统错误";
            if (![responseObject[@"message"] isKindOfClass:[NSNull class]]) {
                message = responseObject[@"message"];
            }
            NSInteger code = [responseObject[@"code"] integerValue];
            NSError *err = [NSError errorWithDomain:@"com.showYork.DDUP" code:code userInfo:@{@"info":message}];
            if ([responseObject[@"code"] intValue] == 1) {
                success(responseObject);
            }else if (code == 10009 || code == 10010){
                // 错误消息
                NSInteger code = [responseObject[@"code"] integerValue];
                NSString *msg = code == 10010?@"帐号异常，请联系客服":@"登录状态已失效，请重新登录";
                NSError *err = nil;
                if ([[RPAppManager jsd_findVisibleViewController] isKindOfClass:[LoginViewController class]] ||
                    [[RPAppManager jsd_findVisibleViewController] isKindOfClass:[RegisterViewController class]] ||
                    [[RPAppManager jsd_findVisibleViewController] isKindOfClass:[BindPhoneViewController class]]) {
                    err = [NSError errorWithDomain:@"com.showYork.DDUP" code:code userInfo:@{@"info":msg}];
                }else{
                    err = [NSError errorWithDomain:@"com.showYork.DDUP" code:code userInfo:@{@"info":@""}];
                }
                failure(err);
                // 移除动画
                if ([[RPAppManager jsd_findVisibleViewController] isKindOfClass:[RPBaseViewController class]]) {
                    [(RPBaseViewController *)[RPAppManager jsd_findVisibleViewController] removeAllHelpView];
                }
                if (![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[LoginViewController class]] &&
                    ![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[RegisterViewController class]] &&
                    ![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[BindPhoneViewController class]]) {
                
                    // 二次判断
                    if ([[RPAppManager jsd_findVisibleViewController] isKindOfClass:[VideoPlayerViewController class]]) {
                        // 关闭播放并且切换屏幕
                        [((VideoPlayerViewController *)[RPAppManager jsd_findVisibleViewController]) stopVideoPlayer];
                    }
                    if ([[RPAppManager jsd_findVisibleViewController] isKindOfClass:[CampusVideoPlayerViewController class]]) {
                        // 关闭播放并且切换屏幕
                        [((CampusVideoPlayerViewController *)[RPAppManager jsd_findVisibleViewController]) stopVideoPlayer];
                    }
                    
                    UIViewController *vc = [RPAppManager jsd_findVisibleViewController];
                    while(vc.presentingViewController != nil){
                        vc = vc.presentingViewController;
                    }
                    // 防止modal的逻辑处理 处理内存泄露
                    [vc dismissViewControllerAnimated:NO completion:nil];
                
                    [UserInfoModel deleteUserInfo];
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    loginVC.isAppLogin = YES;
                    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:loginVC];
                    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                    [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:msg duration:2 finishHandler:nil];
                   
                }
            }else{
                failure(err);
            }
            
        }
    }];
    [task resume];
    
    return task;
}

@end
